# app/utils/extract_text_from_pdf.py

import fitz  # PyMuPDF
from typing import Union, List, Dict
import os

def extract_text_from_pdf(files: Union[str, List[str]]) -> Union[List[str], Dict[str, List[str]]]:
    """
    Extracts text content from a single PDF file or a list of PDF files.

    Args:
        files (str or List[str]): PDF file path(s)

    Returns:
        List[str] for single file or Dict[str, List[str]] for multiple files.
        Each inner list contains text per page.
    """
    if isinstance(files, str):
        return _extract_single_pdf(files)
    
    elif isinstance(files, list):
        result = {}
        for fpath in files:
            if os.path.isfile(fpath) and fpath.lower().endswith(".pdf"):
                result[os.path.basename(fpath)] = _extract_single_pdf(fpath)
        return result

    else:
        raise TypeError("Input must be a file path string or a list of file path strings.")

def _extract_single_pdf(filepath: str) -> List[str]:
    """Extracts text per page from a single PDF."""
    text_pages = []
    try:
        with fitz.open(filepath) as doc:
            for page in doc:
                text_pages.append(page.get_text("text"))
    except Exception as e:
        text_pages.append(f"[Error extracting text: {str(e)}]")
    return text_pages
